<?php 
namespace Shop\Controller;

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel;
use Zend\Db\Adapter\Adapter;
use Zend\Debug\Debug;

class CatalogController extends AbstractActionController 
{
	private $mPage;
	private $mTotalPages;
	private $mProductsPerPage = 8;
	private $mLinkToCurrentPage;
	private $mLinkToNextPage;
	private $mLinkToPreviousPage;
	private $mViewStyle = 'list';
	private $mDepartmentId;
	private $mCategoryId;
	
	public function indexAction()
	{
		//$this->init();
		$data = array(
			'number_of_pages'	=> 9,
			'page_link' => array(
				'style'	=> 'list',
				'depid'	=> 1,
				'catid' => 1,
				'page' => 3,
			),
			'department' => array(
				'name' => 'Televisions',
				'category' => array(
					'name'=> 'LCD',
					'products' => array(
						array(
							'name' => 'Samsung Series 110',
							'thumbnail' => array(
								'image_1' => 'nex.jpg',
								'image_2' => 'allin.jpg',
								'image_3' => 'wii.jpg',
							),
							'price' => 120,
							'in_stock' => 1,
							'product_code' => 'Cyber Shot S1000',
							'brand' => 'Samsung',
							'warranty' => 12,
							'star' => 3,
							'link' => array(
								'proid' => 1,
							)
						),
						array(
							'name' => 'Panasonic 1080 HD',
							'thumbnail' => array(
								'image_1' => 'nex.jpg',
								'image_2' => 'allin.jpg',
								'image_3' => 'wii.jpg',
							),
							'price' => 150,
							'in_stock' => 1,
							'product_code' => 'Cyber Shot S1000',
							'brand' => 'Samsung',
							'warranty' => 12,
							'star' => 4,
							'link' => array(
								'proid' => 2,
							)
						),
					),
				),
			),
		);
		//Debug::dump($data);
		$view = new ViewModel($data);
		if($data['page_link']['style'])
			$view->setTemplate('shop/catalog/listview');
		else
			$view->setTemplate('shop/catalog/gridview');
		
		return $view;
	}
	
	public function getDbAdapter()
	{
		$config = $this->getServiceLocator()->get('Config');
		$DbAdapter = new Adapter($config['db']);
		return $DbAdapter;
	}
	
	private function init()
	{
		// Get View Style from query string casting it to string
		if ($this->getRequest()->getQuery('style'))
			$this->mViewStyle = (string)$this->getRequest()->getQuery('style');
		// Get DepartmentId from query string casting it to int
		if ($this->getRequest()->getQuery('DepartmentId'))
			$this->mDepartmentId = (int)$this->getRequest()->getQuery('depid');
		// Get CategoryId from query string casting it to int
		if ($this->getRequest()->getQuery('catid'))
			$this->mCategoryId = (int)$this->getRequest()->getQuery('catid');
		// Get Page number from query string casting it to int
		if ($this->getRequest()->getQuery('page'))
			$this->mPage = (int)$this->getRequest()->getQuery('page');		

		if ($this->getRequest()->getQuery('catid'))
		{		
			$lstCategories = $this->GetCategoriesOnDepartment($this->mDepartmentId);			
			foreach($lstCategories as $item)
			{
				if($item['id'] == $this->mCategoryId)
				{
					$catRow = $this->GetCategoryDetails($this->mCategoryId)->current();
					$this->mCategoryName = $catRow['name'];
					$depRow = $this->GetDepartmentDetails($this->mDepartmentId)->current();
					$this->mDepartmentName = $depRow['name'];
					$this->mProducts = $this->GetProductsInCategory(
						$this->mCategoryId, $this->mPage, $this->mTotalPages);
				}			
			}						
		}			
		elseif ($this->getRequest()->getQuery('depid'))
		{
			$depRow = $this->GetDepartmentDetails($this->mDepartmentId)->current();
			$this->mDepartmentName = $depRow['name'];
			$this->mProducts = $this->GetProductsOnDepartment(
					$this->mDepartmentId, $this->mPage, $this->mTotalPages);
		}

		//Build Current Page link
		if (isset($this->mCategoryId))
			$this->mLinkToCurrentPage = array(
					'ViewStyle' => $this->mViewStyle,
					'DepartmentId' => $this->mDepartmentId,
					'CategoryId' => $this->mCategoryId,
					'page' => $this->mPage,
			);
		elseif (isset($this->mDepartmentId))
		$this->mLinkToCurrentPage = array(
				'ViewStyle' => $this->mViewStyle,
				'DepartmentId' => $this->mDepartmentId,
				'page' => $this->mPage,
		);
		if ($this->mTotalPages > 1)
		{
			// Build the Next link
			if ($this->mPage < $this->mTotalPages)
			{
				if (isset($this->mCategoryId))
					$this->mLinkToNextPage = array(
						'ViewStyle' => $this->mViewStyle,
						'DepartmentId' => $this->mDepartmentId,
						'CategoryID' => $this->mCategoryId,
						'page' => $this->mPage + 1,
					);
				elseif (isset($this->mDepartmentId))
				$this->mLinkToNextPage = array(
					'ViewStyle' => $this->mViewStyle,
					'DepartmentId' => $this->mDepartmentId,					
					'page' => $this->mPage + 1,
				);
			}
			// Build the Previous link
			if ($this->mPage > 1)
			{
				if (isset($this->mCategoryId))
					$this->mLinkToPreviousPage = array(
						'ViewStyle' => $this->mViewStyle,
						'DepartmentId' => $this->mDepartmentId,
						'CategoryID' => $this->mCategoryId,
						'page' => $this->mPage - 1,
					);
				elseif (isset($this->mDepartmentId))
					$this->mLinkToPreviousPage = array(
						'ViewStyle' => $this->mViewStyle,
						'DepartmentId' => $this->mDepartmentId,					
						'page' => $this->mPage - 1,
					);
			}
		}
		// Build links for product details pages
		/* for ($i = 0; $i < count($this->mProducts); $i++)
		{
			$this->mProducts[$i]['link_to_product'] =
			Link::ToProduct($this->mProducts[$i]['product_id']);
			if ($this->mProducts[$i]['thumbnail'])
			$this->mProducts[$i]['thumbnail'] =
			Link::Build('product_images/' . $this->mProducts[$i]['thumbnail']);
		} */
	}
	
    function HowManyPages($countSql, $countSqlParams)
    {
    	$result = $this->getDbAdapter()->query($countSql, $countSqlParams, Adapter::QUERY_MODE_EXECUTE);
    	$items_count = $result->current()->products_count;
    	// Calculate the number of pages
    	$how_many_pages = ceil($items_count / $this->mProductsPerPage);
    	return $how_many_pages;
    }
    //Retrieves list of categories that belong to a department
    function GetCategoriesOnDepartment($departmentId)
    {
    	$adapter = $this->getDbAdapter();
    	//$fp = function($name) use ($adapter) { return $adapter->driver->formatParameterName($name); };
    	// Build SQL query
    		$sql = "SELECT   id, name, description
					FROM     categories
					WHERE    DepartmentID = %s
					ORDER BY	id;";
    	// Execute the query and return the results
    	$statement = $this->getDbAdapter()->createStatement(sprintf($sql, $departmentId));
    	Debug::dump($statement->execute());
    	return $statement->execute();
    }
    // Retrieves list of products that belong to a category
    function GetProductsInCategory($categoryId, $pageNo, &$rHowManyPages)
    {
    	// Query that returns the number of products in the category
    	$sql = 'CALL catalog_count_products_in_category(:category_id)';
    	// Build the parameters array
    	$params = array(':category_id' => $categoryId);
    	// Calculate the number of pages required to display the products
    	$rHowManyPages = 1; //$this->HowManyPages($sql, $params);
    	// Calculate the start item
    	$start_item = ($pageNo - 1) * $this->mProductsPerPage;
    	// Retrieve the list of products
    	$sql = 'CALL catalog_get_products_in_category(:category_id,:start_item,:products_per_page)';
    	// Build the parameters array
    	$params = array (
    		':category_id' => $categoryId,
    		':start_item' => $start_item,
    		':products_per_page' => $this->mProductsPerPage,
    	);
    	// Execute the query and return the results
    	return $this->getDbAdapter()->query($sql, $params, Adapter::QUERY_MODE_EXECUTE);
    }
    // Retrieves the list of products for the department page
    function GetProductsOnDepartment($departmentId, $pageNo, &$rHowManyPages)
    {
    	// Query that returns the number of products in the department page
    	$sql = 'CALL catalog_count_products_on_department(:department_id)';
    	// Build the parameters array
    	$params = array (':department_id' => $departmentId);
    	// Calculate the number of pages required to display the products
    	$rHowManyPages = $this->HowManyPages($sql, $params);
    	// Calculate the start item
    	$start_item = ($pageNo - 1) * $this->mProductsPerPage;
    	// Retrieve the list of products
    	$sql = 'CALL catalog_get_products_on_department(:department_id,:start_item,:products_per_page)';
    	// Build the parameters array
    	$params = array (
    		':department_id' => $departmentId,
    		':start_item' => $start_item,
    		':products_per_page' => $this->mProductsPerPage
    	);
    	// Execute the query and return the results
    	return $this->getDbAdapter()->query($sql, $params, Adapter::QUERY_MODE_EXECUTE);
    }
    
    function GetCategoryDetails($categoryId)
    {
    	// Build SQL query
    	$sql = 'CALL catalog_get_category_details(:category_id)';
    	// Build the parameters array
    	$params = array (':category_id' => $categoryId);
    	// Execute the query and return the results
    	return $this->getDbAdapter()->query($sql, $params, Adapter::QUERY_MODE_EXECUTE);
    }
    
    function GetDepartmentDetails($departmentId)
    {
    	// Build SQL query
    	$sql = 'CALL catalog_get_department_details(:department_id)';
    	// Build the parameters array
    	$params = array (':department_id' => $departmentId);
    	// Execute the query and return the results
    	return $this->getDbAdapter()->query($sql, $params, Adapter::QUERY_MODE_EXECUTE);
    }
}